﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoAnForum.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Linq.Dynamic;

namespace DoAnForum.Controllers
{
    public class CategoryController : Controller
    {
        private static DoAnForumEntities db = new DoAnForumEntities();
        [AccessDeniedAuthorize(Roles = "Admin")]
        public ActionResult ListCategory()
        {
            Session["includeInActiveCategory"] = false;
            Session["CharFilterCategory"] = "";
            return View();
        }

        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("CategoryStore");

            Session["includeInActiveCategory"] = !(bool)Session["includeInActiveCategory"];

            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CharFilterCategory(string filterstring)
        {
            var store = X.GetCmp<Store>("CategoryStore");
            Session["CharFilterCategory"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        public ActionResult BindingCategoryStore(StoreRequestParameters parameters)
        {
            var sampleData = db.Categories.Select(x => new
                                                           {
                                                               x.CategoriId,
                                                               x.CategoryName,
                                                               x.Description,
                                                               x.Level,
                                                               x.Active
                                                           });


            bool includeInActive = (bool)Session["includeInActiveCategory"];
            string charFilter = (string)Session["CharFilterCategory"];

            var result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active)));
            if ("0".Equals(charFilter))
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) &&
                    (ent.CategoryName.StartsWith("0") || ent.CategoryName.StartsWith("1") ||
                    ent.CategoryName.StartsWith("2") || ent.CategoryName.StartsWith("3") ||
                    ent.CategoryName.StartsWith("4") || ent.CategoryName.StartsWith("5") ||
                    ent.CategoryName.StartsWith("6") || ent.CategoryName.StartsWith("7") ||
                    ent.CategoryName.StartsWith("8") || ent.CategoryName.StartsWith("9")
                    )));
            }

            else
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) && ent.CategoryName.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.CategoriId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData.Select(ent => new { ent.CategoriId, ent.CategoryName, ent.Description, ent.Level, ent.Active }), result.Count());
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "Admin")]
        public ActionResult CreateCategory()
        {
            ViewBag.HideTextBox = false;
            ViewBag.ParentId = new List<ListItem>();
            ViewBag.ParentId = db.Categories.ToList().Select(ent => new ListItem { Text = ent.CategoryName, Value = ent.CategoriId.ToString() });
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [AccessDeniedAuthorize(Roles = "Admin")]
        public ActionResult CreateCategory(Category model)
        {
            if (ModelState.IsValid)
            {
                if (model.ParentId == null) model.Level = 1;
                else
                {
                    var parent = db.Categories.SingleOrDefault(x => x.CategoriId == model.ParentId);
                    if (parent != null) model.Level = parent.Level + 1;
                }
                model.Active = true;
                var currUser = db.aspnet_Users.SingleOrDefault(x => x.UserName == User.Identity.Name);
                if (currUser != null)
                {
                    model.UserId = currUser.UserId;
                    model.LastEditUserId = currUser.UserId;
                }

                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Logo = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }

                db.Categories.AddObject(model);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Create Category success!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Non Sucess", "Create Category non success!").Show();

            return this.FormPanel();
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "Admin")]
        public ActionResult EditCategory(int id)
        {
            ViewBag.HideTextBox = false;
            ViewBag.ParentId = new List<ListItem>();
            ViewBag.ParentId = db.Categories.ToList().Select(ent => new ListItem { Text = ent.CategoryName, Value = ent.CategoriId.ToString() });

            Category category = db.Categories.Single(m => m.CategoriId == id);

            return View(category);
        }

        [HttpPost]
        [ValidateInput(false)]
        [AccessDeniedAuthorize(Roles = "Admin")]
        public ActionResult EditCategory(Category model)
        {
            Category category1 = db.Categories.Single(c => c.CategoriId == model.CategoriId);
            if (ModelState.IsValid)
            {
                if (model.ParentId == null) model.Level = 1;
                else
                {
                    var parent = db.Categories.SingleOrDefault(x => x.CategoriId == model.ParentId);
                    if (parent != null) model.Level = parent.Level + 1;
                }
                var currUser = db.aspnet_Users.SingleOrDefault(x => x.UserName == User.Identity.Name);
                if (currUser != null)
                {
                    model.LastEditUserId = currUser.UserId;
                }

                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Logo = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }
                else
                {
                    model.Logo = category1.Logo;
                }

                db.Categories.Detach(category1);
                db.Categories.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit GroupCategory success!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Sucess", "Edit GroupCategory non success!").Show();
            return this.FormPanel();
        }
    }
}
